<?php

namespace common\models\db;

use Yii;
use yii\web\IdentityInterface;

/**
 * This is the model class for table "tbl_user".
 *
 * @property int $id
 * @property string $open_id 微信小程序用户唯一标识
 * @property string|null $nick_name 用户昵称
 * @property string|null $avatar_url 用户头像URL
 * @property string $created_at 创建时间
 * @property string $updated_at 更新时间
 *
 * @property LoanComparison[] $loanComparisons
 * @property LoanRecord[] $loanRecords
 */
class User extends \yii\db\ActiveRecord implements IdentityInterface
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'tbl_user';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['open_id'], 'required'],
            [['created_at', 'updated_at'], 'safe'],
            [['open_id'], 'string', 'max' => 100],
            [['nick_name'], 'string', 'max' => 50],
            [['avatar_url'], 'string', 'max' => 255],
            [['open_id'], 'unique'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'open_id' => 'Open ID',
            'nick_name' => 'Nick Name',
            'avatar_url' => 'Avatar Url',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
        ];
    }

    /**
     * 通过微信openid查找用户
     *
     * @param string $openid 微信openid
     * @return User|null
     */
    public static function findByOpenid($openid)
    {
        return static::findOne(['open_id' => $openid]);
    }

    /**
     * {@inheritdoc}
     */
    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id]);
    }

    /**
     * {@inheritdoc}
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        // 小程序不使用此方法，返回null
        return null;
    }

    /**
     * {@inheritdoc}
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * {@inheritdoc}
     */
    public function getAuthKey()
    {
        // 小程序不使用此方法，返回空字符串
        return '';
    }

    /**
     * {@inheritdoc}
     */
    public function validateAuthKey($authKey)
    {
        // 小程序不使用此方法，返回true
        return true;
    }

    /**
     * Gets query for [[LoanComparisons]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getLoanComparisons()
    {
        return $this->hasMany(LoanComparison::class, ['user_id' => 'id']);
    }

    /**
     * Gets query for [[LoanRecords]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getLoanRecords()
    {
        return $this->hasMany(LoanRecord::class, ['user_id' => 'id']);
    }
}
